import React, {useEffect, useState, forwardRef, useImperativeHandle, ReactNode} from "react";
import TablePanel from "@/components/table-panel/table-panel";
import SearchPanel from "@/components/search-panel/search-panel";
import request from '@/api/inedx'
import {IParams} from '../table-panel/table-panel'

interface IListProps {
    params: { [key: string]: any },
    headers: any[],
    searchUrl: string,
    isMultiSelect?: boolean,
    isHasOperateColumn?: boolean,
    operateColumnWidth?: number
    children: ReactNode,
    ref?: any,
    resetClick: ()=>void
}

interface IListComponentInstance {
    getTableList: () => void
}

const List: React.FC<IListProps> = forwardRef<IListComponentInstance, IListProps>((props, ref) => {
    useImperativeHandle(ref, () => {
        return {
            getTableList: () => {
                searchData()
            }
        }
    })

    let [data, setData] = useState<any>({
        tableData: [],
        total: 0,
    })
    let [tableParams, setTableParams] = useState({
        pageSize: 10,
        pageNum: 1
    })

    useEffect(() => {
        searchData()
    }, [tableParams])

    const searchData = () => {
        const params = {
            ...props.params,
            ...tableParams
        }
        request.get<ListResponse>(`/api${props.searchUrl}`, {params}).then(res => {
            if (res.status === 0) {
                setData({...data, tableData: res.data.pageData, total: res.data.total})
            }
        })
    }

    const paginationChange = (params: IParams) => {
        setTableParams({...tableParams, ...params})
    }

    const searchClick = () => {
        searchData()
    }

    const resetClick = () => {
        searchData()
        props.resetClick()
    }

    return <div className="list">
        <SearchPanel searchClick={searchClick} resetClick={resetClick}>
            {props.children}
        </SearchPanel>
        <TablePanel tableData={data.tableData} headers={props.headers} paginationChange={paginationChange}></TablePanel>
    </div>
})

export default List

export type {IListComponentInstance}
